package com.example.service.Impl;

import com.example.pojo.Message;
import  com.example.util.JwtUtil;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/ws/{username}")
@Component
@Slf4j
public class WebSocketService {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    private static final Map<String, Session> onLineUsers = new HashMap<>();

    // 推送给房东
    public void sendMessageToOwner(Message message) {
        String destination = "/queue/owner/" + message.getReceiverId() + "/messages";
        messagingTemplate.convertAndSend(destination, message);
    }
    // 推送给用户
    public void sendMessageToUser(Message message) {
        String destination = "/queue/user/" + message.getReceiverId() + "/messages";
        messagingTemplate.convertAndSend(destination, message);
    }

    /**
     * 建立websocket连接后被调用
     * @param session
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("username") String username) {
        log.info("用户：{} 建立连接",username);
        onLineUsers.put(username,session);
    }

    @OnMessage
    public void onMessage(String message,@PathParam("username") String username) {
        log.info("用户：{} 发送消息：{}",username,message);
    }
    @OnClose
    public void onClose(@PathParam("username") String userName,Session session) {
        log.info("用户：{} 关闭连接",userName);
        onLineUsers.remove(userName);
    }
    @OnError
    public void onError(Throwable t) {
      log.info("webSocket发生错误"+t);
    }

    /**
     * 群发
     * @param message
     * @param
     */
    public void sendMessage(String message) {
       Collection<Session> session = onLineUsers.values();
        for (Session s : session){
            try {
                s.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
